class BlockingQueue{
    String[] data = null;
    int head = 0;
    int tail = 0;
    int size = 0;

    public BlockingQueue(int capacity){
        data = new String[capacity];
    }

    public void put(String ele) throws InterruptedException {
        synchronized(this){
            while (size >= data.length){
                //队列满了，需要阻塞。
                //return;
                this.wait();
            }

            data[tail] = ele;
            tail++;
            if (tail > data.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized(this){
            while (size == 0){
                //队列为空，需要阻塞。
                //return null;
                this.wait();
            }

            String tmp = data[head];
            head++;
            if (head == data.length){
                head = 0;
            }
            size--;
            this.notify();
            return tmp;
        }
    }
}

public class Demo4 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
           while (true){
               try {
                   myBlockingQueue.put(n + " ");
                   System.out.println("生产元素： " + n);
                   n++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread customer = new Thread(() -> {
            while (true){
                try {
                    String n = myBlockingQueue.take();
                    System.out.println("消费元素： " + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.start();
        customer.start();
    }
}
